package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.FileUtils;
import com.lxr0860.lxr0860production_test.utils.Utils;
import com.lxr0860.lxr0860production_test.view.CustomDialog;
import com.sdk.devicemanager.DEVICEcon;


/**
 * 打开关闭USB口接口无效
 */
public class USBActivity extends Activity{
    private TextView tvUsbStatus;
    private ToggleButton tbUsb;
    private TextView tvUsbTip;
    private TextView mTvBatteryLevel;
    //    private DEVICEcon_17Y devicEcon;
    private DEVICEcon devicEcon;
    private CustomDialog.Builder builder;
    private int testType;
    private int usbInCount, usbOutCount;
    private static final int STATE_IN = 1;
    private static final int STATE_OUT = 2;
    private int mCurrentState;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Contants.DIALOG_POSITIVE:
                    if (testType == Contants.TEST_QIANGHUA) {
                        Log.e("cly", "usbIn-->" + usbInCount + "--usbOut-->" + usbOutCount);
                        new Thread() {
                            @Override
                            public void run() {
                                FileUtils.writeFile(Contants.LOG_STRENGTH_PATH,
                                        "USB/插" + usbInCount + "次 | 拔" + usbOutCount
                                                + "次/" + Utils.getCurrentDate() + "\r\n");
                            }
                        }.start();
                    } else {
                        Intent mIntent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("result", true);
                        mIntent.putExtras(bundle);
                        USBActivity.this.setResult(Contants.TEST_ITEM_USB, mIntent);
                    }
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    if (testType != Contants.TEST_QIANGHUA) {
                        usbInCount = usbOutCount = 0;
                    }
                    builder = null;
                    break;
            }
        }
    };

    private void init() {
        testType = getIntent().getIntExtra("testType", Contants.TEST_ZUZHUANG);
        tvUsbStatus = (TextView) findViewById(R.id.tvUsbStatus);
        tvUsbTip = (TextView) findViewById(R.id.tvUsbTip);
        tbUsb = (ToggleButton) findViewById(R.id.tbUsb);
        mTvBatteryLevel = (TextView) findViewById(R.id.tv_battery);

//        devicEcon = new DEVICEcon_17Y(this);
        devicEcon = new DEVICEcon(this);
//        devicEcon.setAdbPassword("12345678","12345678");
        tbUsb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                openCloseUsb(b);
            }
        });
        tbUsb.setChecked(true);
        registerBroadcast();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_usb);
        init();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {

            if (event.getKeyCode() == 4 && testType == Contants.TEST_QIANGHUA) {
                if (builder == null) {
                    builder = Contants.showDailog(
                            USBActivity.this, "是否退出USB强化测试", handler, Gravity.TOP);
                }
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    /**
     * 打开关闭USB口
     */
    private void openCloseUsb(boolean isChecked) {
        if (isChecked) {
            boolean open = devicEcon.setAdbEnabled(0, "12345678");
            if (open) {
                tvUsbStatus.setText("ADB打开成功!");
            } else {
                tvUsbStatus.setText("ADB打开失败!");
            }
        } else {
            boolean open = devicEcon.setAdbEnabled(1, "12345678");
            if (open) {
                tvUsbStatus.setText("ADB关闭成功!");
            } else {
                tvUsbStatus.setText("ADB关闭失败!");
            }
        }
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterBroadcasr();
    }

    private USBPlugBroadcast mRecevier;

    private void registerBroadcast() {
        mRecevier = new USBPlugBroadcast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.hardware.usb.action.USB_STATE");
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        USBActivity.this.registerReceiver(mRecevier, filter);
    }


    class USBPlugBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("cly", "action-->" + action);
            if ("android.hardware.usb.action.USB_STATE".equals(action)) {
                Log.e("cly", "USBPlugBroadcast-->" + action);
                boolean connected = intent.getExtras().getBoolean("connected");
                if (connected) {
                    Log.e("cly", "USBPlugBroadcast-->usbIn");
                    if (mCurrentState == STATE_IN) {
                        return;
                    }
                    mCurrentState = STATE_IN;
                    usbInCount++;
                    tvUsbTip.setText("USB已连接 \n请查看电池图标是否处于充电状态");
                } else {
                    Log.e("cly", "USBPlugBroadcast-->usbOut");
                    if (mCurrentState == STATE_OUT) {
                        return;
                    }
                    mCurrentState = STATE_OUT;
                    usbOutCount++;
                    tvUsbTip.setText("USB未连接 !");
                }
                if (usbInCount > 0 && usbOutCount > 0) {
                    if (testType != Contants.TEST_QIANGHUA) {
                        if (builder == null) {
                            builder = Contants.showDailog(
                                    USBActivity.this, "USB正常，是否保存测试", handler, Gravity.TOP);
                        }
                    }
                }
            } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                mTvBatteryLevel.setText("当前电量：" + intent.getIntExtra("level", 0) + "%");
            }
        }
    }

    private void unregisterBroadcasr() {
        if (mRecevier != null) {
            USBActivity.this.unregisterReceiver(mRecevier);
        }
    }
}